//
//  HOTMessageChatViewController.m
//  Genpara
//
//  Created by zhang chunhui on 14-9-27.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTMessageChatViewController.h"
#import "HOTMessageChatForSendCell.h"
#import "HOTMessageChatForReceivedCell.h"
#import "HOTCreateOrderViewController.h"
#import "HOTNavigationViewController.h"
#import "HOTNaviBar.h"
#import "HOTMessageChatForSendProject.h"
#import "HOTMessageChatForReceivedProject.h"
#import "HOTMessageChatForSendImage.h"
#import "HOTMessageChatForReceivedImage.h"
#import "APService.h"


@interface HOTMessageChatViewController ()<UITableViewDataSource, UITableViewDelegate> {
    
    NSMutableArray *_dataList;
    BOOL isAddListener; //判断是否已经添加过jpush的观察者通知
}

@property(nonatomic,strong)NSMutableArray *dataList;
@property(nonatomic,strong)NSMutableDictionary *paramDic;
@property(nonatomic,strong)NSMutableDictionary *msgIdCache; //记录保存所有的message id信息
@property(nonatomic,strong)UIBarButtonItem *rightBarItem;

@end

@implementation HOTMessageChatViewController

@synthesize dataList = _dataList;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
            conv_type:(CONV_TYPE)convType
           target_uid:(NSString *)targetUid
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.convType = convType;
        self.target_id = targetUid;
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated {
    
    
    
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated {
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter removeObserver:self name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNaviTitle:@"メッセージ"];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_message"]];
    
    //[self showChatInputBar:YES];
    
    self.msgIdCache = [NSMutableDictionary dictionary];
    
    _dataList = [[NSMutableArray alloc] initWithCapacity:10];
    
    self.rightBarItem = [self createBarButtomItemTarget:self action:@selector(purchaseOrderBtnClicked) image:[UIImage imageNamed:@"btn_purchaseorder_off"] hImage:[UIImage imageNamed:@"btn_purchaseorder_on"] edgeInsets:UIEdgeInsetsMake(0, 0, 0, -20)];
    
    
    //__unsafe_unretained HOTMessageChatViewController *unretainObj = self;
    
    
    self.paramDic = [NSMutableDictionary dictionary];
    if (self.convType == CONV_TYPE_GENBA) {
        
        //借贷现场聊天的场合
        [self.paramDic setObject:@"1" forKey:REQ_KEY_CONV_TYPE];
        
    } else {
        [self.paramDic setObject:@"0" forKey:REQ_KEY_CONV_TYPE];
    }
    
    [self.paramDic setObject:self.userInfo.userId forKey:REQ_KEY_USER_ID];
    [self.paramDic setObject:self.target_id forKey:REQ_KEY_TARGET_ID];
    [self.paramDic setObject:self.userInfo.token forKey:REQ_KEY_USER_TOKEN];

    [self requestDataFromNet];
}

-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = self.paramDic;
    
    __unsafe_unretained HOTMessageChatViewController *tempObj = self;
    __unsafe_unretained UITableView *tempTableView = _tableView;
    [self requestWithURL:HOT_URL_MESSAGE_INFO Parameters:parameters success:^(NSInteger result, NSDictionary * dic) {
        
        [tempObj loadingSuccess];
        
        self.convId = [dic objectForKey:@"conv_id"];
        NSString *convTypeStr = [dic objectForKey:@"conv_type"];
        
        if ([convTypeStr isEqualToString:@"1"]) {
            
            tempObj.convType = CONV_TYPE_GENBA;
            
            self.navigationItem.rightBarButtonItem = self.rightBarItem;
            [tempObj showChatInputBar:YES withStyle:HOTCharBarStyleForImageProject];
            
        } else {
            
            self.navigationItem.rightBarButtonItem = nil;
            tempObj.convType = CONV_TYPE_OTHER;
            [tempObj showChatInputBar:YES withStyle:HOTCharBarStyleForImageOnly];
        }
        
        [tempObj initChatBar:tempObj];
        
        tempTableView.frame = CGRectMake(tempTableView.frame.origin.x, tempTableView.frame.origin.y, tempTableView.frame.size.width, tempTableView.frame.size.height - tempObj.chatInputBar.frame.size.height);
        
        NSArray *dataArr = [dic objectForKey:@"list"];
        
        for (NSDictionary *valueDic in dataArr) {
            
            [self.msgIdCache setObject:valueDic forKey:[HOTUtils getString:[valueDic objectForKey:@"msg_id"]]];
        }
        
        // 此时添加观察者，是为了先让msgIdCache初始化完成
        if (isAddListener == NO) {
            NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
            [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:)
                                  name:kJPFNetworkDidReceiveMessageNotification object:nil];
            
            isAddListener = YES;
        }
        
        if (dataArr.count == 0) {
          
            
            return;
        }

        [tempObj.dataList addObjectsFromArray:dataArr];

        [tempTableView reloadData];

        if (tempObj.dataList.count > 0) {
            
            
            
            [tempTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:tempObj.dataList.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
        
//        NSDictionary *msgContent = @{@"pic_url":@"",
//                                     @"pic_thumb_url":[NSURL URLWithString:@"file://Users/Kris/Library/Developer/CoreSimulator/Devices/C5F036A2-93EB-43EC-AF34-5885BA4A0CC9/data/Containers/Data/Application/B2A42D3D-E7D3-440E-9BB3-DA36B641A03F/Library/Caches/chat_upImage_1804289383.png"]
//                                     };
//        [tempObj refrashWithMessage:msgContent msgType:1];
        
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
    }];
}

//
//发送对话消息
-(void)sendMsg:(NSString *)msg image:(UIImage *)image msgType:(int)msgType{
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_CONV_ID:self.convId,
                                 REQ_KEY_MSG_CONTENT: [HOTUtils getString:msg],
                                 REQ_KEY_PIC_URL:[HOTUtils getString:msg],
                                 REQ_KEY_MSG_TYPE:[NSString stringWithFormat:@"%d", msgType]};
    [self showLoading];
    __unsafe_unretained HOTMessageChatViewController *tempObj = self;
    [self requestWithURL:HOT_URL_MESSAGE_SEND Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        //发送成功
        
        id msgContent;
        if (msgType == 1) {
            //图片消息
            msgContent = @{@"pic_url":msg,
                           @"pic_thumb_url":image,
                           @"isLocal":@"1"
                           };
        } else {
            
            msgContent = msg;
        }
        
        [tempObj refrashWithMessage:msgContent msgType:msgType];
        
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        //发送失败
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {

            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)initChatBar:(HOTMessageChatViewController *) unretainObj{
    
    self.chatInputBar.sendBtnClicked = ^(NSString *sendMsg) {
        
        [unretainObj sendMsg:sendMsg image:nil msgType:0];
        
        
    };
    
    __unsafe_unretained HOTMessageChatViewController *tempObj = self;
    self.chatInputBar.uploadImageDone = ^(UIImage *image) {
        //上传图片消息的处理
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        
        //NSData *imageData = UIImagePNGRepresentation(selImage);
        
//        long randomName =  random();
//        NSString *fileName = [NSString stringWithFormat:@"chat_upImage_%ld", randomName];
//        
//        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//        path = [path stringByAppendingString:[NSString stringWithFormat:@"/%@.jpg", fileName]];
//        [imageData writeToFile:path atomically:YES];
        
//        NSLog(@"org image path = %@", path);
        
        [tempObj showLoading];
        [tempObj uploadImageWithPost:HOT_URL_UPLOAD imageData:imageData uploadName:@"file_path" Parameters:nil success:^(NSDictionary * data) {
            
            
            NSString *url = [data objectForKey:@"url"];
//            NSLog(@"------- %@",url);
            
            [tempObj sendMsg:url image:image msgType:1];
            
        } failure:^(NSError *error, NSString *errMsg) {
            
            [tempObj loadingSuccess];
            
            if ([tempObj checkErrResult:error errMsg:errMsg]) {
                return ;
            }
            
            if (errMsg.length > 0) {
                
                ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                      message:errMsg
                                                                     delegate:nil
                                                            cancelButtonTitle:nil
                                                             otherButtonTitle:ALERT_BTN_OK];
                
                [popupView showInWindow];
            }
        }];
        
        
    };
    
    //点击了发注书按钮
//    self.chatInputBar.orderBtnClicked = ^(void) {
//        
//        HOTCreateOrderViewController *covc = [[HOTCreateOrderViewController alloc] initWithNibName:@"HOTCreateOrderViewController" bundle:nil convId:unretainObj.convId targetUid:unretainObj.target_id];
//        
//        covc.completion = ^(NSString *url, NSString *orderId) {
//            
//            
//            NSLog(@"order url = %@ \n order id = %@",url, orderId);
//            NSDictionary *msgContent = @{@"status":@"1", @"contract_url":url, @"id":orderId, @"agreement":@""};
//            [unretainObj refrashWithMessage:msgContent msgType:2];
//        };
//        
//        HOTNavigationViewController *baseNavc = [[HOTNavigationViewController alloc] initWithNavigationBarClass:[HOTNaviBar class] toolbarClass:nil];
//        [baseNavc pushViewController:covc animated:NO];
//        
//        
//        [unretainObj presentViewController:baseNavc animated:YES completion:nil];
//    };
}

#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic = [_dataList objectAtIndex:indexPath.row];

    
    if ([[dic objectForKey:@"user_id"] isEqualToString:self.userInfo.userId]) {
        //我发的消息
        NSInteger msgType = [[dic objectForKey:@"msg_type"] integerValue];
        
        if (msgType == 1) {
            //图片消息
            
            static NSString *cellId = @"HOTMessageChatForSendImage";
            HOTMessageChatForSendImage *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForSendImage") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            
            
            [cell setImageContentInfo:[dic objectForKey:@"msg_content"]];
            return cell;
            
        } else if (msgType == 2) {
            //发注书消息
            static NSString *cellId = @"HOTMessageChatForSendProject";
            HOTMessageChatForSendProject *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForSendProject") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            cell.responder = self;
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            
            cell.info = [dic objectForKey:@"msg_content"];
            return cell;
            
        } else {
            //文本消息
            
            static NSString *cellId = @"HOTMessageChatForSendCell";
            HOTMessageChatForSendCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForSendCell") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            //cell.contentLabel.text = [dic objectForKey:@"msg_content"];
            if ([[dic objectForKey:@"msg_type"] integerValue] != 2) {
                cell.contentLabel.text = [dic objectForKey:@"msg_content"];
            }
            return cell;
        }

    } else {
        //接受对方的消息
        
        NSInteger msgType = [[dic objectForKey:@"msg_type"] integerValue];
        
        if (msgType == 1) {
            //图片消息
            static NSString *cellId = @"HOTMessageChatForReceivedImage";
            HOTMessageChatForReceivedImage *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForReceivedImage") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            
            cell.nickImageView.user_id = [dic objectForKey:@"user_id"];
            cell.nickImageView.targetVcClass = [self class];
            
            
            [cell setImageContentInfo:[dic objectForKey:@"msg_content"]];
            return cell;
            
        } else if (msgType == 2) {
        
            //发注书消息
            static NSString *cellId = @"HOTMessageChatForReceivedProject";
            HOTMessageChatForReceivedProject *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForReceivedProject") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            cell.responder = self;
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            
            cell.nickImageView.user_id = [dic objectForKey:@"user_id"];
            cell.nickImageView.targetVcClass = [self class];
            
            cell.info = [dic objectForKey:@"msg_content"];
            return cell;
        } else {
            
            
            static NSString *cellId = @"HOTMessageChatForReceivedCell";
            HOTMessageChatForReceivedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForReceivedCell") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            cell.contentLabel.text = [dic objectForKey:@"msg_content"];
            
            cell.nickImageView.user_id = [dic objectForKey:@"user_id"];
            cell.nickImageView.targetVcClass = [self class];
            
            return cell;
        }
    }
    
    
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic = [_dataList objectAtIndex:indexPath.row];
    
    UITableViewCell *tCell;
    
    if ([[dic objectForKey:@"user_id"] isEqualToString:self.userInfo.userId]) {
        //我发的消息
        NSInteger msgType = [[dic objectForKey:@"msg_type"] integerValue];
        
        if (msgType == 1) {
            //图片消息
            static NSString *cellId = @"HOTMessageChatForSendImage";
            HOTMessageChatForSendImage *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForSendImage") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            
            
            [cell setImageContentInfo:[dic objectForKey:@"msg_content"]];
            tCell = cell;
            
        } else if (msgType == 2) {
            //发注书消息
            static NSString *cellId = @"HOTMessageChatForSendProject";
            HOTMessageChatForSendProject *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForSendProject") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            
            cell.info = [dic objectForKey:@"msg_content"];
            tCell = cell;
            
        } else {
            //文本消息
            
            static NSString *cellId = @"HOTMessageChatForSendCell";
            HOTMessageChatForSendCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForSendCell") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            //cell.contentLabel.text = [dic objectForKey:@"msg_content"];
            if ([[dic objectForKey:@"msg_type"] integerValue] != 2) {
                cell.contentLabel.text = [dic objectForKey:@"msg_content"];
            }
            tCell = cell;
        }
        
        
        [tCell setNeedsDisplay];
        [tCell setNeedsUpdateConstraints];
        [tCell.contentView setNeedsDisplay];
        [tCell.contentView setNeedsUpdateConstraints];
        
        float cellH = [tCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        
//        NSLog(@"cellH = %f",cellH);
        return cellH;
    
    } else {
        //接受对方的消息
        
        
        UITableViewCell *tCell;
        NSInteger msgType = [[dic objectForKey:@"msg_type"] integerValue];
        
        if (msgType == 1) {
            //图片消息
            static NSString *cellId = @"HOTMessageChatForReceivedImage";
            HOTMessageChatForReceivedImage *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForReceivedImage") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            
            
            [cell setImageContentInfo:[dic objectForKey:@"msg_content"]];
            
            tCell = cell;
            
        } else if (msgType == 2) {
            
            //发注书消息
            static NSString *cellId = @"HOTMessageChatForReceivedProject";
            HOTMessageChatForReceivedProject *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForReceivedProject") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            cell.responder = self;
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            
            cell.info = [dic objectForKey:@"msg_content"];
            tCell = cell;
        } else {
            
            
            static NSString *cellId = @"HOTMessageChatForReceivedCell";
            HOTMessageChatForReceivedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            
            if (cell == nil) {
                
                UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageChatForReceivedCell") bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:cellId];
                
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            cell.nickLabel.text = [dic objectForKey:@"user_nick"];
            cell.nickLabel.user_id = [dic objectForKey:@"user_id"];
            cell.nickLabel.targetVcClass = [self class];
            cell.contentLabel.text = [dic objectForKey:@"msg_content"];
            
            tCell = cell;
        }
        
        [tCell setNeedsDisplay];
        [tCell setNeedsUpdateConstraints];
        [tCell.contentView setNeedsDisplay];
        [tCell.contentView setNeedsUpdateConstraints];
        
        float cellH = [tCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
//        NSLog(@"cellH = %f",cellH);
        return cellH;
    }
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

-(void)refrashWithMessage:(id)msgContent msgType:(int)msgType {
    
    [self refrashWithMessage:msgContent msgType:msgType userId:self.userInfo.userId userNick:self.userInfo.nick];
    
}

-(void)refrashWithMessage:(id)msgContent
                  msgType:(int)msgType
                   userId:(NSString *)userId
                 userNick:(NSString *)userNick{
    
    if (msgType == 1) {
        //图片消息
        [_dataList addObject:@{@"msg_content":msgContent, @"msg_type":@"1" , @"user_id":userId, @"user_nick":userNick}];
    } else if (msgType == 2) {
        //发注书消息
        [_dataList addObject:@{@"msg_content":msgContent, @"msg_type":@"2" , @"user_id":userId, @"user_nick":userNick}];
    } else {
        //文本消息
        [_dataList addObject:@{@"msg_content":msgContent, @"msg_type":@"0" , @"user_id":userId, @"user_nick":userNick}];
    }
    
    
    
    NSIndexPath *insertIndex = [NSIndexPath indexPathForRow:_dataList.count-1 inSection:0];
    
    [_tableView insertRowsAtIndexPaths:@[insertIndex] withRowAnimation:UITableViewRowAnimationBottom];
    
    [_tableView scrollToRowAtIndexPath:insertIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];
}




-(void)chatBarFrameWillChange:(CGPoint)newPoint {
    
    _tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, newPoint.y);
}

///接收消息(jpush 自定义消息tcp长连接)
-(void)networkDidReceiveMessage:(NSNotification *)notification {

    //NSData *respones = [[notification.userInfo objectForKey:@"content"] dataUsingEncoding:NSUTF8StringEncoding];
    //id jsonObject = [NSJSONSerialization JSONObjectWithData:[notification.userInfo objectForKey:@"content"] options:NSJSONReadingAllowFragments error:nil];
    
    NSDictionary *userInfo = [notification.userInfo objectForKey:@"content"];
    
//    NSLog(@"聊天消息 %@" ,userInfo);
    
    NSDictionary *content = [userInfo objectForKey:@"content"];
    
    
    NSString *userId = [content objectForKey:@"user_id"];
    NSString *msgId = [content objectForKey:@"msg_id"];
    id data = [self.msgIdCache objectForKey:msgId];
    
    if ([self.target_id isEqualToString:userId] && data == nil) {
        //data == nil 意味着此时收到的消息是新消息，已有的datalist中不存在
        
        int msgType = [[content objectForKey:@"msg_type"] intValue];
        
        NSString *userNick = [content objectForKey:@"user_nick"];
        id msgContent = [content objectForKey:@"msg_content"];
        
        [self refrashWithMessage:msgContent
                         msgType:msgType
                          userId:userId
                        userNick:userNick];
    }
}

//点击发注书按钮
-(void)purchaseOrderBtnClicked {
    
    HOTCreateOrderViewController *covc = [[HOTCreateOrderViewController alloc] initWithNibName:@"HOTCreateOrderViewController" bundle:nil convId:self.convId targetUid:self.target_id];
    
    covc.completion = ^(NSString *url, NSString *orderId) {
        
        
        NSLog(@"order url = %@ \n order id = %@",url, orderId);
        NSDictionary *msgContent = @{@"status":@"1", @"contract_url":url, @"id":orderId, @"agreement":@""};
        [self refrashWithMessage:msgContent msgType:2];
    };
    
    HOTNavigationViewController *baseNavc = [[HOTNavigationViewController alloc] initWithNavigationBarClass:[HOTNaviBar class] toolbarClass:nil];
    [baseNavc pushViewController:covc animated:NO];
    
    
    [self presentViewController:baseNavc animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc {
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter removeObserver:self name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    [defaultCenter removeObserver:self];

}

@end
